<template>
  <div>
    <div style="margin-left: 30px;">
      <span style="color:red;">* </span>赠品
    </div>
    <br>
    <div style="margin-left: 30px;">
       <a-button v-show="!giveawaGoodsList[0]" type="link" @click="choosegiveawaGoods">添加赠品</a-button>
       <div  v-show="giveawaGoodsList[0]">
         <a-button  type="link"  @click="choosegiveawaGoods">修改已选商品</a-button>
         <br>
         <br>
         <div style="display: flex;">
           <div ><table-img style="width: 60px;height: 40px;" :src="src" alt=""/></div>
           <div style="display: flex;flex-direction: column;">
             <div>{{goodName || ""}}</div>
             <div v-show="src!==vipIcon">{{goodsPrice || ""}}元</div>
             <div v-show="src==vipIcon">有效期:{{vipDuration || ""}}</div>
           </div>
           <a-button type="link" style="margin-left: 40px;" @click="deleteGoods">删除</a-button>
         </div>
       </div>
      <br>
      <br>
      <div >
        <span style="color:red;">* </span><span>库存设置</span>
        <br>
        <br>
        <div   style="width: 100%">
          <a-table :columns="giveawaTableColumns"
                   size="small"
                   :data-source="giveawaGoodsList"
                   :row-key="(record) => record.goodsSpecId"
                   :pagination="false"
          >

                  <div slot="deltaStock" slot-scope="text, record">
                    <a-input-number  v-model="record.deltaStock" >

                    </a-input-number>

                  </div>
          </a-table>
          <br>
          <div style="float: right;">
             <a-button type="primary" v-show="giveawaGoodsList.length>0" @click="submitData">确定</a-button>
             <a-button style="margin-left: 15px;" @click="cancel">取消</a-button>
          </div>
        </div>
      </div>
    </div>
    <!--加赠品model-->

    <a-modal
      :visible="giveawaModelVisible"
      okText="选择"
      cancelText="取消"
      :title="title"
      :maskClosable="false"
      :destroyOnClose="true"
      :keyboard="false"
      width="1200px"
      @cancel="closeModal"
      @ok="handleSubmit">
      <a-tabs v-model="tabKey" @change="callback"  >
        <a-tab-pane  :key="1" tab="商品" >
          <SearchTableW
            :url="choosegiveawaGoodsUrl"
            ref="giveawasearchtable"
            :form="giveawaForm"
            :columns="giveawaColumns"
            row-key="id"
            width="1000px"
            tableSelectType="radio"
            :default-params="defaultParams"
          >
            <template slot="searchForm">
              <a-form layout="inline" :form="giveawaForm">

                <a-form-item label="商品名称">
                  <a-input
                    style="width:180px"
                    v-decorator="[
                'goodsName',
              ]"
                    placeholder="请输入商品名称"
                  >
                  </a-input>
                </a-form-item>

                <a-form-item label="商品分类">
                  <a-tree-select
                    allowClear
                    style="width:180px"
                    :replaceFields="{children:'children', title:'classifyName', key:'id', value: 'id' }"
                    v-decorator="[
                'goodsClassificationId',
              ]"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="giveawaProductClassifyList"
                    placeholder="请选择"
                    tree-default-expand-all
                  >
              <span slot="title" slot-scope="{ value }">
                  {{ value }}
              </span>
                  </a-tree-select>
                </a-form-item>

                <a-form-item label="商品分组">
                  <a-tree-select
                    allowClear
                    style="width:180px"
                    :replaceFields="{children:'children', title:'groupName', key:'id', value: 'id' }"
                    v-decorator="[
                  'goodsGroupId',
                ]"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="giveawaProductGroupList"
                    placeholder="请选择"
                    tree-default-expand-all
                  >
                <span slot="title" slot-scope="{ value }">
                    {{ value }}
                </span>
                  </a-tree-select>
                </a-form-item>

              </a-form>
            </template>
          </SearchTableW>
        </a-tab-pane>

        <a-tab-pane  :key="2" tab="付费会员卡" >
          <search-table
            :url="vipCardUrl"
            ref="vipCardsearchtable"
            :form="vipCardForm"
            :columns="vipCardColumns"
            :chosen-keys="vipCardkeys"
            width="1000px"
            tableSelectType="radio"
            row-key="id"
            :default-params="defaultParams2"
          >
            <template slot="searchForm">
              <a-form layout="inline" :form="vipCardForm">

                <a-form-item label="付费会员卡名称">
                  <a-input
                    style="width:180px"
                    v-decorator="[
                      'cardName',
                     ]"
                    placeholder="请选择付费会员卡名称"
                  >
                  </a-input>
                </a-form-item>


              </a-form>
            </template>
          </search-table>
        </a-tab-pane>


        <a-tab-pane  :key="3" tab="自建商品" >
          <search-table
                  :url="selfCreateGoodUrl"
                  ref="selfCreateGoodsearchtable"
                  :form="selfCreateGoodForm"
                  :columns="selfCreateGoodColumns"
                  :chosen-keys="selfCreateGoodkeys"
                  width="1000px"
                  row-key="id"
                  tableSelectType="radio"
          >
            <template slot="searchForm">
              <a-form layout="inline" :form="selfCreateGoodForm">

                <a-form-item label="商品名称">
                  <a-input
                          style="width:180px"
                          v-decorator="[
                      'goodsName',
                     ]"
                          placeholder="商品名称"
                  >
                  </a-input>
                </a-form-item>


              </a-form>
            </template>
          </search-table>
        </a-tab-pane>
      </a-tabs>


    </a-modal>
  </div>
</template>

<script>
  import SearchTableW from "./SearchTableW";
  import SearchTable from "./SearchTableW/SearchTable";
  export default {
    name: "addGoods",
    components:{
      SearchTableW,
      SearchTable
    },
    computed: {
      userInfo(){
        return this.$store.getters.userInfo || {};
      },
      // 是否可编辑 ★★★★★
      editable(){
      /*  let list = []
        this.giveawaGoodsList.forEach((item,index)=>{
          list.push(item.goodsSpecId)
        })
        console.log(list,this.selectedRowKeys[0])
      return !list.includes(this.selectedRowKeys[0])*/
      }
    },
    watch:{

    },
    data(){
      return{
          tabKey:1,
          goodsPrice:'',
          goodName:'',

          defaultParams:{
            marketingType:2// 2021/11/18
          },
          title:"选择赠品",
          src:'',
          giveawaForm: this.$form.createForm(this, { name: 'table_search' }),
          choosegiveawaGoodsUrl:'/goods/page',
          giveawaModelVisible:false,
          giveawaGoodskeys:[],
          giveawaGoodsList:[],
          goodsType:'',
          giveawaProductClassifyList: [],//商品类型
          giveawaProductGroupList:[],
          giveawaColumns:[
          {
            title: '商品名称',
            dataIndex: 'goodsName',
            key: 'goodsName',
          },

          {
            title: '价格',
            dataIndex: 'salePrice',
            key: 'salePrice',
            customRender:(text,row)=>{
              return (text/100).toFixed(2)+"元"
            }
          },
          {
            title: '总可售库存',
            dataIndex: 'goodsInventoryTotal',
            key: 'goodsInventoryTotal',
          },
          /*  {
              title: '销量',
              dataIndex: 'realSales',
              key: 'realSales',
            },*/

          {
            title: '状态',
            dataIndex: 'goodsStatus',
            key: 'goodsStatus',
            customRender: (text, record) => {
              switch (text) {
                case 1:
                  return "仓库中";
                case 2:
                  return "上架";
                case 3:
                  return "已下架";
                case 4:
                  return "已售完";
              }
            }
          },

          {
            title: '创建时间',
            dataIndex: 'createDate',
            key: 'createDate',
          },
        ],
          giveawaTableColumns: [
          {
            title: '商品名称',
            dataIndex: 'goodsName',
            key: 'goodsName',
            align: 'center',
            customRender:(text,row)=>{
              return <div class="product_td"><table-img src={row.goodsPicture ||row.vipIcon}/><div class="product_name">{text}</div></div>
            }
          },
          {
            title: '商品规格',
            dataIndex: 'norm',
            key: 'norm',
            align: 'center',
            customRender:(text,row)=>{
              if (text==null && row.goodsSpecId ==1){
                  return "有效期:1年"
              }
             else if (text==null && row.goodsSpecId ==2){
                return "有效期:3个月"
              }
             else  if (text==null && row.goodsSpecId ==3){
                return "有效期:1个月"
              }
             else {
                return  text
              }
            }
          },
          {
            title: '商品实际库存数',
            dataIndex: 'goodsStock',
            key: 'goodsStock'
          },
          {
            title: '增减赠品库存数量',
            dataIndex: 'deltaStock',
            key: 'deltaStock',
            align: 'center',
            scopedSlots: {customRender: 'deltaStock'}
          },
          {
            title: '赠品总库存数',
            dataIndex: 'stock',
            key: 'stock',
            align: 'center',
          },
          {
            title: '赠品剩余库存数',
            dataIndex: 'remainingStock',
            key: 'remainingStock',
            align: 'center',
          },
          {
            title: '赠品已被领取',
            dataIndex: 'prizePoolStock',
            key: 'prizePoolStock'
          },
       /*   {
          title: '赠品已被领取',
          dataIndex: 'prizePoolStock',
          key: 'prizePoolStock',
        },*/
          {
            title: '赠品已被使用',
            dataIndex: 'used',
            key: 'used',
          }
        ],

          // tabkey =2
          vipCardForm: this.$form.createForm(this, { name: 'table_search' }),
          vipCardUrl: 'goldenhome/member/admin_/member/card/page',
          vipCardModelVisible:false,
          vipDuration:'',
          defaultParams2:{
            receiveWay: 2
          },
          vipCardkeys:[],
          vipCardColumns: [
          {
            title: '付费会员名称',
            dataIndex: 'cardName',
            key: 'cardName',
          },
          {
            title: '领取方式',
            dataIndex: 'way',
            key: 'way',
            customRender: (text, row) => {
               return row.receiveWay == 1? "付费购买":"发放领取"
              /*  return {
                  children:(row.receiveWay == 1?(<span>付费购买</span>):(<span>发放领取</span>)),
                  attrs:{}
                }*/
            }
          },
          {
            title: '领取规则',
            dataIndex: 'payRuleResponseList',
            key: 'payRuleResponseList',
            customRender: (text, row) => {
              var result = ''
              if (row.payRuleResponseList != null) {
                result = row.payRuleResponseList.reduce((pre, cur) => {
                  switch (cur.validPeriodUnit) {
                    case 1:
                      return pre += "" + cur.validPeriodUnit + "年" + "￥:" + cur.price + "元 ;"
                    case 2:
                      return pre += "1季度(3个月)" + "￥:" + cur.price + "元 ;"
                    case 3:
                      return pre += "1个月" + "￥:" + cur.price + "元 ;"

                  }
                }, "")

              }
              return result
            }
          },
          {
            title: '会员权益',
            dataIndex: 'benefitList',
            key: 'benefitList',
            customRender:(text,row)=>{
              return(
                text.map((item,index) =>{
                  return <span>
                            <span v-show={index!=text.length-1}> {item},<span v-show={index>0 && index%2==0}><p></p></span></span>
                            <span v-show={index==text.length-1}>{item} </span>
                        </span>


                })
              )
            }
          },
          {
            title: '创建时间',
            dataIndex: "createDate",
            key: "createDate"
          },
          {
            title: '最后编辑时间',
            dataIndex: "updateDate",
            key: "updateDate"
          },
          {
            title: '会员数',
            dataIndex: 'memberCount',
            key: 'memberCount',
          },
            {
                title: '状态',
                dataIndex: 'isEnabled',
                key: 'isEnabled',
                customRender:(text,row)=>{
                  return text ==1?"已启用":"未启用"
                }
            },
      /*    {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            scopedSlots: {customRender: 'operation'}
          }*/
        ],
          vipIcon:require('@/assets/vipbgc/icon/middle_modalbox_icon_viplevel05@2x.png'),

          //  tabkey = 3
        selfCreateGoodForm: this.$form.createForm(this, { name: 'table_search' }),
        selfCreateGoodUrl: 'goldenhome/gh/lottery_/admin/self/buildgoods/page',

        selfCreateGoodkeys:[],
        selfCreateGoodColumns: [
        {
          title: '商品名称',
          dataIndex: 'goodsName',
          key: 'goodsName',
          // align: 'center',
          customRender:(text,row)=>{
            return <div class="product_td"><table-img src={row.goodsPicture}/><div class="product_name">{text}</div></div>
          }
        },
        {
          title: '商品总数',
          dataIndex: 'stock',
          key: 'stock'
        },
        {
          title: '商品实际剩余库存数',
          dataIndex: 'remainStock',
          key: 'remainStock'
        },
        {
          title: '赠品库领用',
          dataIndex: 'manageStock',
          key: 'manageStock',
          align: 'center'
        },

        {
          title: '已被用户领取',
          dataIndex: 'received',
          key: 'received',
        },
        {
          title: '创建时间',
          dataIndex: 'createDate',
          key: 'createDate',
        },
      /*  {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          scopedSlots: {customRender: 'operation'}
        }*/
      ],
      }
    },
    methods:{
      callback(index){
        /*切换 tab 的时候 清空另一个数组*/
        console.log(index)
   /*     if (index ==1){
          this.$refs.vipCardsearchtable.selectedRowKeys = []
          this.$refs.selfCreateGoodsearchtable.selectedRowKeys = []
        }
        if (index == 2){
          this.$refs.giveawasearchtable.selectedRowKeys = []
          this.$refs.selfCreateGoodsearchtable.selectedRowKeys = []
        }
        if (index == 3){
          this.$refs.vipCardsearchtable.selectedRowKeys = []
          this.$refs.giveawasearchtable.selectedRowKeys = []
        }*/
      },

      deleteGoods(){
        // 删除也要区别 删的是哪个
        this.giveawaGoodskeys = []
        this.giveawaGoodsList =  []
        this.src = ''
      },
      async choosegiveawaGoods(){
        this.giveawaModelVisible = true
        await this.getProductClassify()
        await this.getProductGroup()
        console.log('选择商品model')
      },
      closeModal(){
        this.giveawaModelVisible = false
      },

      //商品分类
      async getProductClassify() {
        let res = await this.$get('/goods/classify/tree', {
          shopId:this.userInfo.shopId || '',
          a:'a'
        });
        if (res && res.returnCode == '1000') {
          this.giveawaProductClassifyList = res.dataInfo || [];
        } else {
          this.giveawaProductClassifyList = [];
        }
      },
      //商品分组
      async getProductGroup() {
        let res = await this.$get('/goods/group/tree', {
          shopId:this.userInfo.shopId || ''
        }, false, true);
        if (res && res.returnCode == '1000') {
          this.giveawaProductGroupList = res.dataInfo || [];
        } else {
          this.giveawaProductGroupList = [];
        }
      },

      async  handleSubmit(){
        console.log("tabkey:",this.tabKey)
        /*根据 tabkey 来确认 选择哪个赠品*/
        if (this.tabKey == 1 ){

          this.giveawaGoodskeys = this.$refs.giveawasearchtable.selectedRowKeys
          let goodsInfo = this.$refs.giveawasearchtable.selectedRows
          this.src = goodsInfo[0].goodsPicture
          this.goodName = goodsInfo[0].goodsName
          this.goodsPrice = goodsInfo[0].salePrice /100
          let goodsType =1
          this.goodsType =1
          console.log(goodsInfo)
          this.giveawaGoodsList = await this.getGoodsListByIds(this.giveawaGoodskeys ,goodsType)
          // 可能需要遍历动态添加stock属性与初始值
          // this.giveawaGoodsList = this.$refs.giveawasearchtable.selectedRows
          this.giveawaGoodsList.forEach((item,index)=>{
            this.$set(item,'goodsPicture',goodsInfo[0].goodsPicture)
            this.$set(item,'goodsName',goodsInfo[0].goodsName)
            this.$set(item,'goodsId',goodsInfo[0].id)
            this.$set(item,'deltaStock',0)
          })
          console.log(this.giveawaGoodsList)
          this.giveawaModelVisible = false
        }

        if (this.tabKey == 2){
          this.giveawaGoodskeys = this.$refs.vipCardsearchtable.selectedRowKeys
          let goodsInfo = this.$refs.vipCardsearchtable.selectedRows
          console.log(goodsInfo);
          // this.giveawaGoodsList  = this.$refs.vipCardsearchtable.selectedRows
          let goodsType = 2
          this. goodsType = 2
          this.giveawaGoodsList = await this.getGoodsListByIds(this.giveawaGoodskeys,goodsType)
          console.log(this.giveawaGoodsList)
          this.src = this.vipIcon
          this.goodName =  goodsInfo[0].cardName
          // 图片要自己引入
          if (!!goodsInfo[0].payRuleResponseList[0].validPeriodUnit && goodsInfo[0].payRuleResponseList[0].validPeriodUnit==1){
            this.vipDuration = "1年"
          }
          if (!!goodsInfo[0].payRuleResponseList[0].validPeriodUnit && goodsInfo[0].payRuleResponseList[0].validPeriodUnit==2){
            this.vipDuration = "3个月"
          }
          if (!!goodsInfo[0].payRuleResponseList[0].validPeriodUnit && goodsInfo[0].payRuleResponseList[0].validPeriodUnit==3){
            this.vipDuration = "1个月"
          }
          // this.src = goodsInfo[0].goodsPicture
          console.log(this.giveawaGoodsList )

          this.giveawaGoodsList.forEach((item,index)=>{

            this.$set(item,'goodsPicture',this.vipIcon)
            this.$set(item,'goodsName',goodsInfo[0].cardName)
            this.$set(item,'goodsId',goodsInfo[0].id)
            this.$set(item,'deltaStock',0)
            this.$set(item,'norm',this.vipDuration)
            this.$set(item,'goodsStock','不限量')
            this.$set(item,'goodsSpecId',0)

          })

          // 可能需要遍历动态添加stock属性与初始值
          // this.giveawaGoodsList = this.$refs.giveawasearchtable.selectedRows

          console.log(this.giveawaGoodsList)
          this.giveawaModelVisible = false

        }

        if (this.tabKey == 3){
          this.selfCreateGoodkeys = this.$refs.selfCreateGoodsearchtable.selectedRowKeys
          let goodsInfo = this.$refs.selfCreateGoodsearchtable.selectedRows
          console.log(goodsInfo);
          this.src = goodsInfo[0].goodsPicture
          this.goodName = goodsInfo[0].goodsName
          console.log(goodsInfo[0]?.salePrice);
          this.goodsPrice = goodsInfo[0]?.salePrice ?? (0+"")
          let goodsType =3
          this.goodsType =3
          this.giveawaGoodsList = await this.getGoodsListByIds(this.selfCreateGoodkeys ,goodsType)
          this.giveawaGoodsList.forEach((item,index)=>{
            this.$set(item,'goodsPicture',goodsInfo[0].goodsPicture)
            this.$set(item,'goodsName',goodsInfo[0].goodsName)
            this.$set(item,'goodsId',goodsInfo[0].id)
            this.$set(item,'deltaStock',0)//
            this.$set(item,'goodsStock',goodsInfo[0].remainStock)//
            this.$set(item,'norm',"统一规格")//
            this.$set(item,'goodsSpecId',"0")
          })
          console.log(this.giveawaGoodsList)
          this.giveawaModelVisible = false
          // console.log(this.selfCreateGoodkeys);
        }
        // console.log( this.giveawaGoodskeys,this.giveawaGoodsList)

      },
      // 根据商品id获取全部规格表格
      async getGoodsListByIds(goodsId,goodsType){
        console.log(goodsId)
        // let ids = goodsIdList.join(',')
        // console.log({ids})
        const res = await this.$get('goldenhome/gh/lottery_/admin/giving/goodsmanage/query',{goodsId:!!goodsId[0]?goodsId[0]:goodsId[0],goodsType})
        if (res && res.returnCode === 1000) {
          console.log('***********')
          console.log(res.dataInfo)
          return res.dataInfo.specList || []
        }
      },

      submitData(){
        console.log("提交数据:",this.giveawaGoodsList)
        let allZero = this.giveawaGoodsList.filter(item => !item.deltaStock || item.deltaStock==0 || item.deltaStock==0)
        if(allZero.length == this.giveawaGoodsList.length) {
          console.log('add 全部为0')
        }
        let goodsId = this.giveawaGoodsList[0].goodsId
       /* let goodsSpecId = this.selectedRows[0].goodsSpecId
        let stock = this.selectedRows[0].stock  add||update*/
        this.$post('goldenhome/gh/lottery_/admin/giving/goodsmanage/update',{
          goodsId,
          goodsSpecList:this.giveawaGoodsList,
          goodsType:this.goodsType
        }).then((res)=>{
          if (res && res.returnCode === 1000) {
            console.log('***********')
            this.$message.success('添加成功')
            // 页面跳转一下
            this.$router.push({
              name: 'MarketingGiveaway',
            })
          }
        })
      },
      cancel(){
        this.$router.push({
          name: 'MarketingGiveaway',
        })
        console.log("取消返回赠品主页面")
      }
    }
  }
</script>

<style scoped lang="less">
  .product_td{
    display: flex;
    align-items: center;
  .product_name{
    margin-left:6px;
  }
  }

</style>